
<template>
  <div>
    <a-upload
      :headers="tokenHeader"
      action="/api/common/upload"
      list-type="picture-card"
      class="avatar-uploader"
      :before-upload="beforeUpload"
      @success="onSuccess"
      @preview="handlePreview"
      @change="handleUploadChange"
      :on-error="onError">
      <div>
        <a-icon type="plus" />
        <div class="ant-upload-text">
          上传作品
        </div>
      </div>
    </a-upload>
    <a-modal :visible="previewVisible" :footer="null" @cancel="handleCancel">
      <img alt="example" style="width: 100%" :src="previewImage" />
    </a-modal>
  </div>
</template>

<script>
import { Upload, Button, Icon } from 'ant-design-vue';
function getBase64(file) {
  return new Promise((resolve, reject) => {
    const reader = new FileReader();
    reader.readAsDataURL(file);
    reader.onload = () => resolve(reader.result);
    reader.onerror = error => reject(error);
  });
}
export default {
  data() {
    return {
      tokenHeader: {token: localStorage.getItem('token')},
      fileObj: {
        name: '',
        url: '',
      },
      previewVisible: false,
      previewImage: '',
    };
  },
  components: {
    'a-upload': Upload,
    'a-button': Button,
    'a-icon': Icon,
  },
  methods: {
    async handlePreview(file) {
      if (!file.url && !file.preview) {
        file.preview = await getBase64(file.originFileObj);
      }
      this.previewImage = file.url || file.preview;
      this.previewVisible = true;
    },
    handleCancel() {
      this.previewVisible = false;
    },
    beforeUpload(file) {
      console.log('beforeUpload', file);
      this.fileObj.name = file.name;
      return true;
    },
    onSuccess(response, file, fileList) {
      console.log('onSuccess-------', response, file, fileList);
    },
    onError(error, response, file) {
      console.log('onError', error, response, file);
    },
    handleUploadChange(info) {
      // 只处理上传完成状态
      if (info.file.status === 'done') {
        console.log('文件上传完成', info.file);
        const upfiles = info.fileList;
        // 在这里调用业务接口
        let formData = new FormData();
        formData.append('file', info.file.originFileObj);
        this.$request.post('api/common/upload', formData).then(res => {
          if (res.code == 1) {
            // console.log(res.data, 'res.datares.datares.data');
            this.fileObj.url = res.data.fullurl;
            this.$emit('uploadSuccess', this.fileObj, upfiles);
          } else {
            this.$message.error(res.msg)
          }
        })
      }
      // 忽略其他状态（added, uploading）
    }
  },
};
</script>

<style>
.avatar-uploader > .ant-upload {
  width: 128px;
  height: 128px;
}
.ant-upload-select-picture-card i {
  font-size: 32px;
  color: #999;
}

.ant-upload-select-picture-card .ant-upload-text {
  margin-top: 8px;
  color: #666;
}
</style>